package peer.rudp.message;


import java.net.DatagramPacket;

import peer.Config;
import peer.Message;
import peer.tools.ByteIntSwitch;
import peer.tools.ByteShortSwitch;


public class DataMessage extends Message{
	short ver=Config.ver;
	short sType=peer.tools.MessageType.sType_DataMessage;
	int sequence=0;
	short length=0;
	byte [] data;
	byte [] dpData;
	public DataMessage(short tunnelId,int sequence,byte[] data,int offset,short length){
		this.sequence=sequence;
		this.length=(short) (length+2);
		this.data=new byte[this.length];
		System.arraycopy(data, offset, this.data, 2, length);
		ByteShortSwitch.toByteArray(tunnelId, this.data, 0);
		dpData=new byte[this.length+12];
		ByteShortSwitch.toByteArray(ver, dpData, 0);  //add: ver
		ByteShortSwitch.toByteArray(sType, dpData, 2);  //add: service type
		ByteIntSwitch.toByteArray(this.sequence, dpData, 4); //add: sequence
		ByteShortSwitch.toByteArray(this.length, dpData, 8); //add:length
		System.arraycopy(this.data, 0, dpData, 10, this.length);
		dp=new DatagramPacket(dpData,dpData.length);
	}
	
	public DataMessage(DatagramPacket dp){
		this.dp=dp;
		dpData=dp.getData();
		ver=ByteShortSwitch.toShort(dpData, 0);
		sType=ByteShortSwitch.toShort(dpData, 2);
		sequence=ByteIntSwitch.toInt(dpData, 4);
		length=ByteShortSwitch.toShort(dpData, 8);
		data=new byte[length];
		System.arraycopy(dpData, 10, data, 0, length);
	}
	
	public int getSequence(){
		return sequence;
	}
	
	 public byte[] getData(){
		return data;
	}
	 
	public int getLength(){
		return length;
	}
}
